package com.ants.modules.quartz.job;

import com.ants.common.utils.CheckBaiduIncludeUrlUtil;
import com.ants.modules.ArticleManage.entity.ArticleManage;
import com.ants.modules.ArticleManage.service.ArticleManageService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * TODO
 * Author Chen
 * Date   2021/12/10 10:17
 */
@Slf4j
public class CheckBaiduIncludeUrlJob implements Job {

    /**
     * 若参数变量名修改 QuartzJobController中也需对应修改
     */
    private String parameter;

    public void setParameter(String parameter) {
        this.parameter = parameter;
    }

    @Autowired
    ArticleManageService articleManageService;
    @Autowired
    private AmqpTemplate rabbitTemplate;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        LambdaQueryWrapper<ArticleManage> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ArticleManage::getIsIncluded, "0");

        // update-begin-author:chenshuang date:2022-08-05   向百度普通收录只推送发布状态=已发送的文章
        lqw.eq(ArticleManage::getPublishState, "1");
        // update-end-author:chenshuang date:2022-08-05   向百度普通收录只推送发布状态=已发送的文章

        List<ArticleManage> list = articleManageService.list(lqw);
        for (ArticleManage articleManage : list) {
            String html = CheckBaiduIncludeUrlUtil.checkBaiduInclude("https://www.wxmin.cn/articleDetails/" + articleManage.getId());
            if (!"".equals(html)) {
                Document doc = Jsoup.parse(html);
                Element element = doc.getElementsByClass("content_none").first();
                if (null == element) {
                    // 百度已经收录该网址，修改收录状态为 是
                    articleManage.setIsIncluded("1");
                    articleManageService.updateIsIncluded("1", articleManage.getId());
                    log.info("百度已经收录该网址");
                } else {
                    // 百度没有收录该网址，继续提交百度收录
                    rabbitTemplate.convertAndSend("pushBaiDuQueue", "https://www.wxmin.cn/articleDetails/" + articleManage.getId());
                    log.info("百度没有收录该网址");
                }
            } else {
//                // 百度没有收录该网址，继续提交百度收录
                rabbitTemplate.convertAndSend("pushBaiDuQueue", "https://www.wxmin.cn/articleDetails/" + articleManage.getId());
                log.info("百度没有收录该网址");
            }
        }
    }

}
